<?php
/**
 * Created by PhpStorm.
 * User: zyw
 * Date: 2018-03-17
 * Time: 16:28
 */

class SmsCodeModel extends MY_Model{

    public $table = 't_sms_code';
    public function __construct(){
        parent::__construct();
    }

    /**
     * 获取验证码
     * @param array $where
     * @return mixed
     */
    public function getCode($where = array()){
        $this->db->where($where);
        $this->db->order_by("add_time", "desc");
        return $this->db->get($this->table)->row_array();
    }

    /**
     * 获取最新验证码
     * @param $mobile
     * @return string
     * @throws Exception
     */
    public function getNewCode($mobile){
        $where = array("mobile" => $mobile, "status" => 0);
        $codeModel = $this->getCode($where);
        if(!empty($codeModel)){
            return $codeModel["code"];
        }
        $arr = array();
        $i = 0;
        while($i < 6){
            $s = rand(0,9);
            $arr[] = $s;
            $i++;
        }
        $code = implode("",$arr);
        $param = array("mobile" => $mobile, "code" => $code,"add_time" => time());
        $id = $this->insert_one($param);
        if($id){
            return $code;
        }
        return "";
    }
}